const async = require("async");
const requireEx=require('yi-require');
const lookup = require('yi-lookup');

const beforeSend = function (req,body,callback) {
  let conversationList = (body.data instanceof Array)?body.data:body.data.items;
  let userID = req.params.userId;

  conversationList.forEach((obj)=>{
    for(let i=0;i<obj.talkerIDArray.length;i++){
      if(obj.talkerIDArray[i].toString()!==userID.toString()){
        obj.fromUserId = obj.talkerIDArray[i];
        break;
      }
    }
  });

  let lookupList = [];
  lookupList.push({
    from:"user",
    localField:"fromUserId",
    foreignField:"_id",
    project:{headPicPath:1,nickname:1}
  }) ;

  lookup.lookup(req.mongo,conversationList,lookupList,(e,r)=>{
    callback(null,body);
  });
};

const middleware = function(req,res,next){
  let userID = req.params.userId;
  req.query =  req.query ||{};
  req.query.filter =  req.query.filter ||{}
  req.mongo.collection("user").find({"_id":userID}).next((e,r)=>{
    if(e) return res.err.mongoError(e);
    req.query.filter._id ={
      "$in":r.conversationIDArray
    };
    req.query.filter.talkerIDArray ={
      "$in":[userID]
    };
    req.beforeSend = beforeSend;
    next();
  });
};

module.exports = {
  open:false,
  description:'根据用户ID获取会话',
  middleware:middleware,
  handler:requireEx('yi-restful').r('conversation')
}